<template>
  <div class="box">
    <h1>科研信息填写系统</h1>
    <el-card id="el-card233" v-loading="loginloading" shadow="always">
      <el-tabs stretch v-model="activeName">
        <el-tab-pane label="登录" name="login">
          <el-form
            label-position="top"
            label-width="80px"
            status-icon
            :model="form1"
            :rules="rules"
            ref="form1"
            hide-required-asterisk
          >
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form1.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input show-password v-model="form1.password" placeholder="请填写密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                key="login-button"
                class="blockButton"
                :type="adlogin == '管理员登录' ? 'primary' : 'danger'"
                @click="submitForm('form1', $event)"
                >登 录</el-button
              >
            </el-form-item>
            <div class="otherButton">
              <el-button type="text" @click="sendFindPwd">忘记密码</el-button>
              <el-button type="text" @click="adminLogin">{{ adlogin }}</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-form
            status-icon
            :model="form2"
            :rules="rules"
            ref="form2"
            label-position="top"
            label-width="80px"
            hide-required-asterisk
          >
            <el-form-item label="邀请码" prop="inviteCode">
              <el-input key="register-code" v-model="form2.inviteCode" placeholder="请输入管理员告知的邀请码"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input key="register-email" v-model="form2.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input key="register-pwd" show-password v-model="form2.password" placeholder="请设置密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button key="register-button" class="blockButton" type="primary" @click="submitForm('form2', $event)"
                >注 册</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
let BaaS = window.BaaS;
import $ from "jquery";
import { findData } from "@/assets/crud";
import md5 from "js-md5";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 验证邀请码
    var isThisCode = (rule, value, callback) => {
      if (value) {
        this.findInviteCode(md5(value), callback);
      } else {
        return;
      }
    };
    return {
      loginloading: false,
      adlogin: "管理员登录",
      activeName: "login",
      // regStatus: 1,
      // regButton: "注册",
      form1: {
        email: "",
        password: "",
      },
      form2: {
        inviteCode: "",
        email: "",
        password: "",
      },
      rules: {
        inviteCode: [
          { required: true, message: "请输入邀请码", trigger: "blur" },
          { validator: isThisCode, trigger: "blur" },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
          {
            required: true,
            message: "请输入邮箱",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "请填写密码",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  //监听属性
  computed: {},
  //监控data中的数据变化
  watch: {
    // 验证邮箱按钮
    // regStatus: function(val) {
    //   if (val == 2) {
    //     this.regButton = "我已验证，进入系统";
    //   }
    // },
    // 登录界面动态效果
    activeName() {
      let el1 = $("#pane-login");
      let el2 = $("#pane-register");
      let el3 = $("#el-card233");
      if (this.activeName == "login") {
        el1.addClass("hide-Tab");
        el2.removeClass("hideTab");
        el3.css("height", "419.8px");
      }
      if (this.activeName == "register") {
        el2.addClass("hideTab");
        el1.removeClass("hide-Tab");
        el3.css("height", "492.2px");
      }
    },
  },
  //方法集合
  methods: {
    // 切换管理员登录
    adminLogin() {
      if (this.adlogin == "管理员登录") {
        this.adlogin = "普通用户登录";
      } else {
        this.adlogin = "管理员登录";
      }
    },
    // 发送忘记密码邮件
    sendFindPwd() {
      this.$prompt("请输入您的邮箱", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: "邮箱格式不正确",
      })
        .then(({ value }) => {
          BaaS.auth
            .requestPasswordReset({ email: value })
            .then(() => {
              this.$message({
                type: "success",
                message: "重置密码邮件已发送",
                center: true,
              });
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "失败，请稍后重试",
                center: true,
              });
            });
        })
        .catch((err) => err);
    },
    // 查找验证码
    findInviteCode(code, callback) {
      let query = new BaaS.Query();
      query.compare("code", "=", code);
      findData("setting", query, "created_at")
        .then((res) => {
          if (res.data.objects.length) {
            callback();
          } else {
            callback(new Error("邀请码错误"));
          }
        })
        .catch((err) => err);
    },
    // 注册函数
    registerFun() {
      BaaS.auth
        .register({
          email: this.form2.email,
          password: this.form2.password,
        })
        .then((user) => {
          if (user) {
            // this.goToCheckEmail();
            // this.regStatus = 2;
            this.loginloading = true;
            return user.set("inviteCode", md5(this.form2.inviteCode)).update();
          }
        })
        .then(() => {
          this.$message.success("注册成功！正在进入系统");
          setTimeout(() => {
            window.$login = true;
            this.$router.replace("/home");
          }, 1500);
        })
        .catch((err) => {
          let message;
          if (err.data.error_msg == "'Email'lready exists.") {
            message = "该邮箱已被注册，请更换邮箱进行注册";
          } else {
            message = "注册失败，请稍后重试";
          }
          this.$alert(message, {
            confirmButtonText: "好的",
            showClose: false,
            center: true,
          });
        });
    },
    // 到时候用小程序封装promise办法试一下，解决return返回值问题
    submitForm(formName, e) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.activeName == "register") {
            // if (this.regStatus == 1) {
            this.registerFun();
            // } else if (this.regStatus == 2) {
            //   BaaS.auth
            //     .getCurrentUser()
            //     .then((user) => {
            //       if (!user.get("_email_verified")) {
            //         this.$confirm("系统检测到邮箱尚未验证", {
            //           confirmButtonText: "超时? 重新发送验证邮件",
            //           cancelButtonText: "好的，前往验证",
            //           type: "error",
            //         }).then(() => {
            //           this.goToCheckEmail();
            //         });
            //       } else {
            //         this.loginloading = true;
            //         BaaS.auth
            //           .getCurrentUser()
            //           .then((user) => {
            //             return user.set("inviteCode", md5(this.form2.inviteCode)).update();
            //           })
            //           .then(() => {
            //             setTimeout(() => {
            //               window.$login = true;
            //               this.$router.replace("/home");
            //             }, 250);
            //           })
            //           .catch(() => {
            //             this.$message.error("失败，请检查网络");
            //           });
            //       }
            //     })
            //     .catch(() => {
            //       this.$message.error("失败，请检查网络");
            //     });
            // }
          } else {
            this.loginloading = true;
            BaaS.auth
              .login({ email: this.form1.email, password: this.form1.password })
              .then(() => {
                this.checkAdmin();
              })
              .catch(() => {
                this.loginloading = false;
                this.$alert("登录失败，请检查填写是否正确，及网络是否通畅", {
                  confirmButtonText: "确定",
                  showClose: false,
                  center: true,
                });
              });
          }
        } else {
          return false;
        }
      });
      e.target.blur();
    },
    // 判断是否交错登录
    checkAdmin() {
      BaaS.auth.getCurrentUser().then((user) => {
        if (!user.get("admin") && this.adlogin == "普通用户登录") {
          this.$message.warning("当前登录为普通用户");
        }
        if (user.get("admin") && this.adlogin == "管理员登录") {
          this.$message.warning("当前登录为管理员");
        }
        BaaS.storage.set("ok", user.get("admin"));
        window.$login = true;
        this.$router.replace("/home");
      });
    },
    // 发送验证
    // goToCheckEmail() {
    //   BaaS.auth
    //     .getCurrentUser()
    //     .then((user) => {
    //       return user.requestEmailVerification();
    //     })
    //     .then(() => {
    //       this.$message({
    //         showClose: true,
    //         message: "已发送验证邮件到您的邮箱，10分钟内有效",
    //         type: "success",
    //         duration: 6000,
    //       });
    //     })
    //     .catch(() => {
    //       this.$message.error("失败，请检查网络");
    //     });
    // },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // this.findInviteCode();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  beforeRouteEnter(to, from, next) {
    if (!from.path) {
      BaaS.auth
        .getCurrentUser()
        .then(() => {
          window.$login = true;
          next({ name: "table" });
        })
        .catch(() => {
          next();
        });
    } else {
      next();
    }
  },
};
</script>
<style scoped>
.box {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 90px;
}
.el-card {
  width: 360px;
}
.blockButton {
  width: 100%;
}
.otherButton {
  display: flex;
  justify-content: space-between;
}
.hideTab {
  animation: hideIndex 0.5s;
}
@keyframes hideIndex {
  0% {
    opacity: 0;
    transform: translate(360px, 0);
  }
  100% {
    opacity: 1;
    transform: translate(0, 0);
  }
}
.hide-Tab {
  animation: hide-Index 0.5s;
}
@keyframes hide-Index {
  0% {
    opacity: 0;
    transform: translate(-360px, 0);
  }
  100% {
    opacity: 1;
    transform: translate(0, 0);
  }
}
#el-card233 {
  transition: height 0.5s;
  height: 419.8px;
}
</style>
